package com.smart.community.region.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.enums.SystemStatusEnum;
import com.smart.community.commons.result.PageResult;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.region.dto.PaymentInfoDTO;
import com.smart.community.region.dto.ShopRentRecordDTO;
import com.smart.community.region.entity.ShopRentRecord;
import com.smart.community.region.mapper.ShopRentRecordMapper;
import com.smart.community.region.service.IShopRentRecordService;
import com.smart.community.region.vo.ShopRentRecordVO;
import com.smart.community.region.vo.ShopRentStatisticsVO;
import com.smart.community.feign.property.service.DataScopeFeign;
import com.smart.community.commons.cache.DataScopeInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 店铺租金记录Service实现类
 * 
 * @author Wu.Liang
 * @version 1.0.0
 * @since 2025-01-30
 */
@Slf4j
@Service
public class ShopRentRecordServiceImpl extends ServiceImpl<ShopRentRecordMapper, ShopRentRecord> implements IShopRentRecordService {
    
    @Autowired
    private ShopRentRecordMapper shopRentRecordMapper;
    
    @Autowired
    private DataScopeFeign dataScopeFeign;
    
    @Override
    public PageResult<ShopRentRecordVO> getRentRecordPage(Integer current, Integer size, Long shopId, Long ownerId, Integer paymentStatus, String rentPeriod, String rentMonth, LocalDate startDate, LocalDate endDate) throws Exception {
        log.info("分页查询租金记录: current={}, size={}, shopId={}, ownerId={}, paymentStatus={}, rentPeriod={}, rentMonth={}, startDate={}, endDate={}", 
            current, size, shopId, ownerId, paymentStatus, rentPeriod, rentMonth, startDate, endDate);
        
        try {
            // 获取当前用户ID
            Long currentUserId = SecurityUtils.getCurrentUserId();
            if (currentUserId == null) {
                log.warn("用户未登录，无法查询租金记录");
                return createEmptyPageResult(current, size);
            }
            
            // 获取用户数据权限范围
            DataScopeInfo userDataScope = dataScopeFeign.getUserDataScope(currentUserId);
            if (userDataScope == null) {
                log.warn("获取用户数据权限范围失败，用户ID：{}，返回空结果", currentUserId);
                return createEmptyPageResult(current, size);
            }
            
            log.info("用户数据权限信息：用户ID={}, 是否超级管理员={}, 是否物业公司用户={}, 社区ID列表={}", 
                currentUserId, userDataScope.isSuperAdmin(), userDataScope.isPropertyCompanyUser(), userDataScope.getCommunityIds());
            
            // 超级管理员，可以查看所有数据
            if (userDataScope.isSuperAdmin()) {
                log.info("用户{}为超级管理员，可以查看所有租金记录", currentUserId);
                return getRentRecordPageWithoutPermission(current, size, shopId, ownerId, paymentStatus, rentPeriod, rentMonth, startDate, endDate);
            }
            
            // 物业公司用户，只查询关联社区的店铺租金记录
            List<Long> communityIds = userDataScope.getCommunityIds();
            if (communityIds == null || communityIds.isEmpty()) {
                log.warn("用户{}无权限访问任何社区数据，返回空结果", currentUserId);
                return createEmptyPageResult(current, size);
            }
            
            log.info("用户{}数据权限过滤完成，可访问社区数量：{}，社区IDs：{}", currentUserId, communityIds.size(), communityIds);
            
            // 根据社区权限查询租金记录
            return getRentRecordPageWithPermission(current, size, shopId, ownerId, paymentStatus, rentPeriod, rentMonth, startDate, endDate, communityIds);
            
        } catch (Exception e) {
            log.error("分页查询租金记录失败，用户ID：{}，错误：{}", SecurityUtils.getCurrentUserId(), e.getMessage(), e);
            return createEmptyPageResult(current, size);
        }
    }
    
    @Override
    @Cacheable(value = "rentRecord:detail", key = "#id")
    public ShopRentRecordVO getRentRecordById(Long id) throws Exception {
        log.info("根据ID查询租金记录: id={}", id);
        
        try {
            if (id == null || id <= 0) {
                throw new IllegalArgumentException("租金记录ID不能为空或小于等于0");
            }
            
            // 数据权限验证
            validateDataPermissionForQuery(id);
            
            // 使用Mapper方法查询包含店铺信息的租金记录详情
            ShopRentRecordVO rentRecordVO = shopRentRecordMapper.selectRentRecordDetailById(id);
            if (rentRecordVO == null) {
                log.warn("租金记录不存在，ID: {}", id);
                return null;
            }
            
            log.info("根据ID查询租金记录成功，ID: {}, 店铺名称: {}", id, rentRecordVO.getShopName());
            return rentRecordVO;
            
        } catch (IllegalArgumentException e) {
            log.warn("根据ID查询租金记录参数错误: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("根据ID查询租金记录失败，ID: {}", id, e);
            throw new RuntimeException("查询租金记录失败，请稍后重试");
        }
    }
    
    @Override
    @Cacheable(value = "rentRecord:list", key = "'shop_' + #shopId")
    public List<ShopRentRecordVO> getRentRecordsByShopId(Long shopId) throws Exception {
        log.info("根据店铺ID查询租金记录: shopId={}", shopId);
        
        try {
            if (shopId == null || shopId <= 0) {
                throw new IllegalArgumentException("店铺ID不能为空或小于等于0");
            }
            
            // 数据权限验证
            validateDataPermissionForQuery(shopId);
            
            // 构建查询条件
            QueryWrapper<ShopRentRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("shop_id", shopId);
            queryWrapper.eq("deleted", 0); // 未删除的记录
            queryWrapper.orderByDesc("create_time");
            
            List<ShopRentRecord> rentRecords = list(queryWrapper);
            
            // 转换为VO列表
            List<ShopRentRecordVO> rentRecordVOs = rentRecords.stream()
                    .map(record -> {
                        ShopRentRecordVO vo = new ShopRentRecordVO();
                        BeanUtils.copyProperties(record, vo);
                        return vo;
                    })
                    .collect(Collectors.toList());
            
            log.info("根据店铺ID查询租金记录成功，店铺ID: {}, 记录数量: {}", shopId, rentRecordVOs.size());
            return rentRecordVOs;
            
        } catch (IllegalArgumentException e) {
            log.warn("根据店铺ID查询租金记录参数错误: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("根据店铺ID查询租金记录失败，店铺ID: {}", shopId, e);
            throw new RuntimeException("查询租金记录失败，请稍后重试");
        }
    }
    
    
    @Override
    @Cacheable(value = "rentRecord:list", key = "'payment_' + #paymentStatus")
    public List<ShopRentRecordVO> getRentRecordsByPaymentStatus(Integer paymentStatus) throws Exception {
        log.info("根据支付状态查询租金记录: paymentStatus={}", paymentStatus);
        
        try {
            if (paymentStatus == null) {
                throw new IllegalArgumentException("支付状态不能为空");
            }
            
            // 验证支付状态值
            if (!SystemStatusEnum.ENABLED.getCode().equals(paymentStatus) && 
                !SystemStatusEnum.DISABLED.getCode().equals(paymentStatus)) {
                throw new IllegalArgumentException("支付状态值只能是0（未支付）或1（已支付）");
            }
            
            // 数据权限验证
            validateDataPermissionForQuery(null);
            
            // 构建查询条件
            QueryWrapper<ShopRentRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("payment_status", paymentStatus);
            queryWrapper.eq("deleted", 0); // 未删除的记录
            queryWrapper.orderByDesc("create_time");
            
            List<ShopRentRecord> rentRecords = list(queryWrapper);
            
            // 转换为VO列表
            List<ShopRentRecordVO> rentRecordVOs = rentRecords.stream()
                    .map(record -> {
                        ShopRentRecordVO vo = new ShopRentRecordVO();
                        BeanUtils.copyProperties(record, vo);
                        return vo;
                    })
                    .collect(Collectors.toList());
            
            log.info("根据支付状态查询租金记录成功，支付状态: {}, 记录数量: {}", paymentStatus, rentRecordVOs.size());
            return rentRecordVOs;
            
        } catch (IllegalArgumentException e) {
            log.warn("根据支付状态查询租金记录参数错误: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("根据支付状态查询租金记录失败，支付状态: {}", paymentStatus, e);
            throw new RuntimeException("查询租金记录失败，请稍后重试");
        }
    }
    
    @Override
    @Cacheable(value = "rentRecord:list", key = "'period_' + #rentPeriod")
    public List<ShopRentRecord> getRentRecordsByPeriod(String rentPeriod) throws Exception {
        log.info("根据租金期间查询租金记录: rentPeriod={}", rentPeriod);
        
        try {
            if (!StringUtils.hasText(rentPeriod)) {
                throw new IllegalArgumentException("租金期间不能为空");
            }
            
            // 数据权限验证
            validateDataPermissionForQuery(null);
            
            // 构建查询条件
            QueryWrapper<ShopRentRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("rent_period", rentPeriod);
            queryWrapper.eq("deleted", 0); // 未删除的记录
            queryWrapper.orderByDesc("create_time");
            
            List<ShopRentRecord> rentRecords = list(queryWrapper);
            
            log.info("根据租金期间查询租金记录成功，期间: {}, 记录数量: {}", rentPeriod, rentRecords.size());
            return rentRecords;
            
        } catch (IllegalArgumentException e) {
            log.warn("根据租金期间查询租金记录参数错误: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("根据租金期间查询租金记录失败，期间: {}", rentPeriod, e);
            throw new RuntimeException("查询租金记录失败，请稍后重试");
        }
    }
    
    @Override
    @Cacheable(value = "rentRecord:list", key = "'date_' + #startDate + '_' + #endDate")
    public List<ShopRentRecord> getRentRecordsByDateRange(LocalDate startDate, LocalDate endDate) throws Exception {
        log.info("根据日期范围查询租金记录: startDate={}, endDate={}", startDate, endDate);
        
        try {
            if (startDate == null || endDate == null) {
                throw new IllegalArgumentException("开始日期和结束日期不能为空");
            }
            
            if (startDate.isAfter(endDate)) {
                throw new IllegalArgumentException("开始日期不能晚于结束日期");
            }
            
            // 数据权限验证
            validateDataPermissionForQuery(null);
            
            // 构建查询条件
            QueryWrapper<ShopRentRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.ge("rent_start_date", startDate);
            queryWrapper.le("rent_end_date", endDate);
            queryWrapper.eq("deleted", 0); // 未删除的记录
            queryWrapper.orderByDesc("create_time");
            
            List<ShopRentRecord> rentRecords = list(queryWrapper);
            
            log.info("根据日期范围查询租金记录成功，开始日期: {}, 结束日期: {}, 记录数量: {}", startDate, endDate, rentRecords.size());
            return rentRecords;
            
        } catch (IllegalArgumentException e) {
            log.warn("根据日期范围查询租金记录参数错误: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("根据日期范围查询租金记录失败，开始日期: {}, 结束日期: {}", startDate, endDate, e);
            throw new RuntimeException("查询租金记录失败，请稍后重试");
        }
    }
    
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @CacheEvict(value = {"rentRecord:page", "rentRecord:list", "rentRecord:detail"}, allEntries = true)
    public Long createRentRecord(ShopRentRecordDTO rentRecordDTO) throws Exception {
        log.info("创建租金记录: {}", rentRecordDTO);
        
        try {
            // 参数验证
            validateRentRecordDTO(rentRecordDTO);
            
            // 数据权限验证
            validateDataPermission(Arrays.asList(rentRecordDTO.getShopId()));
            
            // 转换DTO为实体
            ShopRentRecord rentRecord = new ShopRentRecord();
            BeanUtils.copyProperties(rentRecordDTO, rentRecord);
            
            // 设置审计字段
            LocalDateTime now = LocalDateTime.now();
            Long currentUserId = SecurityUtils.getCurrentUserId();
            rentRecord.setCreateTime(now);
            rentRecord.setUpdateTime(now);
            rentRecord.setCreateBy(currentUserId);
            rentRecord.setUpdateBy(currentUserId);
            rentRecord.setDeleted(0); // 未删除
            
            // 保存到数据库
            boolean saveResult = save(rentRecord);
            if (!saveResult) {
                throw new RuntimeException("保存租金记录失败");
            }
            
            log.info("创建租金记录成功，ID: {}", rentRecord.getId());
            return rentRecord.getId();
            
        } catch (IllegalArgumentException e) {
            log.warn("创建租金记录参数错误: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("创建租金记录失败", e);
            throw new RuntimeException("创建租金记录失败，请稍后重试");
        }
    }
    
    @Override
    public Boolean updateRentRecord(ShopRentRecordDTO rentRecordDTO) throws Exception {
        // TODO: 实现更新租金记录逻辑
        log.info("更新租金记录: {}", rentRecordDTO);
        
        // 转换DTO为实体
        ShopRentRecord rentRecord = new ShopRentRecord();
        BeanUtils.copyProperties(rentRecordDTO, rentRecord);
        
        // 更新到数据库
        return this.updateById(rentRecord);
    }
    
    @Override
    public Boolean payRent(Long recordId, PaymentInfoDTO paymentInfo) throws Exception {
        // TODO: 实现支付租金逻辑
        log.info("支付租金: recordId={}, paymentInfo={}", recordId, paymentInfo);
        
        // 查询租金记录
        ShopRentRecord rentRecord = this.getById(recordId);
        if (rentRecord == null) {
            throw new RuntimeException("租金记录不存在");
        }
        
        // 更新支付状态
        rentRecord.setPaymentStatus(1); // 已支付
        rentRecord.setPaymentMethod(paymentInfo.getPaymentMethod());
        rentRecord.setInvoiceNumber(paymentInfo.getInvoiceNumber());
        
        return this.updateById(rentRecord);
    }
    
    @Override
    public Boolean deleteRentRecord(Long id) throws Exception {
        // TODO: 实现删除租金记录逻辑
        log.info("删除租金记录: id={}", id);
        
        // 逻辑删除
        return this.removeById(id);
    }
    
    @Override
    public Integer countRentRecords(Long shopId, Integer paymentStatus) throws Exception {
        // TODO: 实现统计租金记录数量逻辑
        log.info("统计租金记录数量: shopId={}, paymentStatus={}", shopId, paymentStatus);
        return 0;
    }
    
    @Override
    public java.math.BigDecimal sumRentAmount(Long shopId, Integer paymentStatus) throws Exception {
        // TODO: 实现统计租金总金额逻辑
        log.info("统计租金总金额: shopId={}, paymentStatus={}", shopId, paymentStatus);
        return java.math.BigDecimal.ZERO;
    }
    
    @Override
    public ShopRentStatisticsVO getRentStatistics(Long shopId, LocalDate startDate, LocalDate endDate) throws Exception {
        // TODO: 实现获取租金统计信息逻辑
        log.info("获取租金统计信息: shopId={}, startDate={}, endDate={}", shopId, startDate, endDate);
        
        // 临时返回空统计结果
        ShopRentStatisticsVO statistics = new ShopRentStatisticsVO();
        statistics.setTotalRecords(0L);
        statistics.setTotalRentAmount(java.math.BigDecimal.ZERO);
        statistics.setPaidRecords(0L);
        statistics.setPaidAmount(java.math.BigDecimal.ZERO);
        statistics.setUnpaidRecords(0L);
        statistics.setUnpaidAmount(java.math.BigDecimal.ZERO);
        statistics.setOverdueRecords(0L);
        statistics.setOverdueAmount(java.math.BigDecimal.ZERO);
        statistics.setPaymentRate(java.math.BigDecimal.ZERO);
        statistics.setAverageRentAmount(java.math.BigDecimal.ZERO);
        
        return statistics;
    }
    
    /**
     * 创建空的分页结果
     */
    private PageResult<ShopRentRecordVO> createEmptyPageResult(Integer current, Integer size) {
        PageResult<ShopRentRecordVO> result = new PageResult<>();
        result.setRecords(new ArrayList<>());
        result.setTotal(0L);
        result.setCurrent(current);
        result.setSize(size);
        return result;
    }
    
    /**
     * 无权限限制的分页查询
     */
    private PageResult<ShopRentRecordVO> getRentRecordPageWithoutPermission(Integer current, Integer size, Long shopId, Long ownerId, Integer paymentStatus, String rentPeriod, String rentMonth, LocalDate startDate, LocalDate endDate) throws Exception {
        log.info("无权限限制分页查询租金记录: current={}, size={}, shopId={}, ownerId={}, paymentStatus={}, rentPeriod={}, rentMonth={}, startDate={}, endDate={}", 
            current, size, shopId, ownerId, paymentStatus, rentPeriod, rentMonth, startDate, endDate);
        
        try {
            // 创建分页对象
            Page<ShopRentRecordVO> page = new Page<>(current, size);
            
            // 调用Mapper查询
            IPage<ShopRentRecordVO> result = shopRentRecordMapper.selectRentRecordPageWithoutPermission(page, shopId, ownerId, paymentStatus, rentPeriod, rentMonth, startDate, endDate);
            
            // 转换为PageResult
            PageResult<ShopRentRecordVO> pageResult = new PageResult<>();
            pageResult.setRecords(result.getRecords());
            pageResult.setTotal(result.getTotal());
            pageResult.setCurrent((int) result.getCurrent());
            pageResult.setSize((int) result.getSize());
            
            log.info("无权限限制分页查询完成: 总数={}, 当前页={}, 每页大小={}", result.getTotal(), result.getCurrent(), result.getSize());
            return pageResult;
            
        } catch (Exception e) {
            log.error("无权限限制分页查询失败: {}", e.getMessage(), e);
            return createEmptyPageResult(current, size);
        }
    }
    
    /**
     * 带权限限制的分页查询
     */
    private PageResult<ShopRentRecordVO> getRentRecordPageWithPermission(Integer current, Integer size, Long shopId, Long ownerId, Integer paymentStatus, String rentPeriod, String rentMonth, LocalDate startDate, LocalDate endDate, List<Long> communityIds) throws Exception {
        log.info("带权限限制分页查询租金记录: current={}, size={}, shopId={}, ownerId={}, paymentStatus={}, rentPeriod={}, rentMonth={}, startDate={}, endDate={}, communityIds={}", 
            current, size, shopId, ownerId, paymentStatus, rentPeriod, rentMonth, startDate, endDate, communityIds);
        
        try {
            // 创建分页对象
            Page<ShopRentRecordVO> page = new Page<>(current, size);
            
            // 调用Mapper查询
            IPage<ShopRentRecordVO> result = shopRentRecordMapper.selectRentRecordPageWithPermission(page, shopId, ownerId, paymentStatus, rentPeriod, rentMonth, startDate, endDate, communityIds);
            
            // 转换为PageResult
            PageResult<ShopRentRecordVO> pageResult = new PageResult<>();
            pageResult.setRecords(result.getRecords());
            pageResult.setTotal(result.getTotal());
            pageResult.setCurrent((int) result.getCurrent());
            pageResult.setSize((int) result.getSize());
            
            log.info("带权限限制分页查询完成: 总数={}, 当前页={}, 每页大小={}", result.getTotal(), result.getCurrent(), result.getSize());
            return pageResult;
            
        } catch (Exception e) {
            log.error("带权限限制分页查询失败: {}", e.getMessage(), e);
            return createEmptyPageResult(current, size);
        }
    }
    
    /**
     * 数据权限验证（批量操作）
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     */
    private void validateDataPermission(List<Long> shopIds) throws Exception {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            throw new IllegalArgumentException("用户未登录，无法执行操作");
        }
        
        try {
            // 获取用户数据权限范围
            DataScopeInfo userDataScope = dataScopeFeign.getUserDataScope(currentUserId);
            if (userDataScope == null) {
                throw new IllegalArgumentException("获取用户数据权限范围失败");
            }
            
            // 超级管理员，可以操作所有数据
            if (userDataScope.isSuperAdmin()) {
                log.info("用户{}为超级管理员，可以操作所有租金记录", currentUserId);
                return;
            }
            
            // 物业公司用户，需要验证店铺权限
            if (userDataScope.isPropertyCompanyUser()) {
                List<Long> communityIds = userDataScope.getCommunityIds();
                if (communityIds == null || communityIds.isEmpty()) {
                    throw new IllegalArgumentException("用户无权限访问任何社区数据");
                }
                
                // 验证店铺是否属于用户有权限的社区
                // 这里需要调用店铺服务验证店铺所属社区
                log.info("用户{}数据权限验证完成，可访问社区数量：{}", currentUserId, communityIds.size());
            } else {
                throw new IllegalArgumentException("用户无权限执行此操作");
            }
            
        } catch (Exception e) {
            log.error("数据权限验证失败，用户ID：{}，错误：{}", currentUserId, e.getMessage(), e);
            throw new IllegalArgumentException("数据权限验证失败：" + e.getMessage());
        }
    }
    
    /**
     * 数据权限验证（查询操作）
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     */
    private void validateDataPermissionForQuery(Long shopId) throws Exception {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            throw new IllegalArgumentException("用户未登录，无法执行查询");
        }
        
        try {
            // 获取用户数据权限范围
            DataScopeInfo userDataScope = dataScopeFeign.getUserDataScope(currentUserId);
            if (userDataScope == null) {
                throw new IllegalArgumentException("获取用户数据权限范围失败");
            }
            
            // 超级管理员，可以查询所有数据
            if (userDataScope.isSuperAdmin()) {
                log.info("用户{}为超级管理员，可以查询所有租金记录", currentUserId);
                return;
            }
            
            // 物业公司用户，需要验证店铺权限
            if (userDataScope.isPropertyCompanyUser()) {
                List<Long> communityIds = userDataScope.getCommunityIds();
                if (communityIds == null || communityIds.isEmpty()) {
                    throw new IllegalArgumentException("用户无权限访问任何社区数据");
                }
                
                // 如果指定了店铺ID，需要验证店铺权限
                if (shopId != null) {
                    // 这里需要调用店铺服务验证店铺所属社区
                    log.info("用户{}查询店铺{}的租金记录，权限验证通过", currentUserId, shopId);
                }
                
                log.info("用户{}数据权限验证完成，可访问社区数量：{}", currentUserId, communityIds.size());
            } else {
                throw new IllegalArgumentException("用户无权限执行此查询");
            }
            
        } catch (Exception e) {
            log.error("数据权限验证失败，用户ID：{}，错误：{}", currentUserId, e.getMessage(), e);
            throw new IllegalArgumentException("数据权限验证失败：" + e.getMessage());
        }
    }
    
    /**
     * 租金记录DTO参数验证
     * 遵循《Java后端SpringBoot代码开发规范_重构版.md》Service层规范
     */
    private void validateRentRecordDTO(ShopRentRecordDTO rentRecordDTO) throws Exception {
        if (rentRecordDTO == null) {
            throw new IllegalArgumentException("租金记录信息不能为空");
        }
        
        if (rentRecordDTO.getShopId() == null || rentRecordDTO.getShopId() <= 0) {
            throw new IllegalArgumentException("店铺ID不能为空或小于等于0");
        }
        
        if (rentRecordDTO.getRentAmount() == null || rentRecordDTO.getRentAmount().compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("租金金额不能为空且必须大于0");
        }
        
        if (rentRecordDTO.getRentStartDate() == null) {
            throw new IllegalArgumentException("租金开始日期不能为空");
        }
        
        if (rentRecordDTO.getRentEndDate() == null) {
            throw new IllegalArgumentException("租金结束日期不能为空");
        }
        
        if (rentRecordDTO.getRentStartDate().isAfter(rentRecordDTO.getRentEndDate())) {
            throw new IllegalArgumentException("租金开始日期不能晚于结束日期");
        }
        
        if (rentRecordDTO.getPaymentStatus() == null || 
            (!SystemStatusEnum.ENABLED.getCode().equals(rentRecordDTO.getPaymentStatus()) && 
             !SystemStatusEnum.DISABLED.getCode().equals(rentRecordDTO.getPaymentStatus()))) {
            throw new IllegalArgumentException("支付状态值只能是0（未支付）或1（已支付）");
        }
    }
}
